﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Add_Form
{
    public partial class ICM_Purchase_Order_Contract : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        IBLLMasterContact bllContact = new MasterContactBLL();
        IBLLSysDurationType bllDurationType = new SysDurationTypeBLL();
        PurchaseOrderInstallmentItemBLL bllInstallItem = new PurchaseOrderInstallmentItemBLL();
        BidderBLL bllBidder = new BidderBLL();
        PurchaseOrderCommitteeBLL bllPoCommittee = new PurchaseOrderCommitteeBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();
        private const int ItemsPerRequest = 10;
        IBLLMasterCommitteeFunction bllComFunction = new MasterCommitteeFunctionBLL();
        IBLLMasterCommitteePosition bllComPosition = new MasterCommitteePositionBLL();
        SysPenaltyCountBLL bllPenaltyCount = new SysPenaltyCountBLL();
        SysPenaltyRateTypeBLL bllPenaltyRateType = new SysPenaltyRateTypeBLL();
        PurchaseOrderBLL bllPurchaseOrder = new PurchaseOrderBLL();
        PurchaseRequestBLL bllPurchaseRequest = new PurchaseRequestBLL();
        IBLLPersonal bllPersonal = new PersonalBLL();
        SysCollateralTypeBLL bllColType = new SysCollateralTypeBLL();
        SysCollateralCategoryBLL bllColcategory = new SysCollateralCategoryBLL();
        double totalExvat = 0;
        double totalVat = 0;
        double totalAmount = 0;
        private bool isItemInEditMode = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //tab ข้อมูลหลัก
                GetContactDetail();
                LoadDurationType();
                //tab รายการพัสดุ
                LoadGridItem();
                //tab คณะกรรมการ
                LoadGridCommittee();
                LoadCommitteeFunction();
                LoadCommitteePosition();
                tipCommitteeHistory.TargetControls.Add(History_Committee.ClientID, true);
                //tab กำหนดการปรับ
                LoadGridPenalty();
                LoadPenaltyCount();
                LoadPenaltyRateType();
                //tab หลักประกัน
                LoadGridCollateral();
                LoadCollateralCateory();
                LoadCollateralType();
                //tab เอกสารแนบ
                LoadGridFile();
                LoadGridInstallment();
                panelDateReq.Attributes.Add("style", "visibility:hidden");
                panelDateReqPick.Attributes.Add("style", "visibility:hidden");
                panelLeast.Attributes.Add("style", "visibility:hidden");
                panelSeparateReason.Attributes.Add("style", "visibility:hidden");
                rdbDuration.Attributes.Add("onclick", "return ChangeDurationRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                rdbDate.Attributes.Add("onclick", "return ChangeDateRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                rdbSeparate.Attributes.Add("onclick", "return ChangeSeparate('" + panelSeparateReason.ClientID + "')");
                rdbNoSeparate.Attributes.Add("onclick", "return ChangeNoSeparate('" + panelSeparateReason.ClientID + "')");
                txtDate.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Today);
                CalendarDate.FocusedDate = DateTime.Today;
                CalendarDate.SelectedDate = DateTime.Today;
                hdBidderSeq.Value = GetBidderSeq().ToString();
            }

            if (rdbDate.Checked)
            {
                panelDuration.Attributes.Add("style", "visibility:hidden");
                panelDateReq.Attributes.Add("style", "visibility:visible");
                panelDateReqPick.Attributes.Add("style", "visibility:visible");
                hdDurationDate.Value = txtDateReq.TextWithLiterals;
                hdCheckDuration.Value = "0";
            }
            if (rdbDuration.Checked)
            {
                panelDuration.Attributes.Add("style", "visibility:visible");
                panelDateReq.Attributes.Add("style", "visibility:hidden");
                panelDateReqPick.Attributes.Add("style", "visibility:hidden");
                hdDurationTypeSeq.Value = cbDurationType.SelectedValue;
                hdDurationTypeText.Value = cbDurationType.Text;
                hdDuration.Value = txtDurationReq.Text;
                hdCheckDuration.Value = "1";
            }
            if (rdbSeparate.Checked)
            {
                panelSeparateReason.Attributes.Add("style", "visibility:hidden");
            }
            if (rdbNoSeparate.Checked)
            {
                panelSeparateReason.Attributes.Add("style", "visibility:visible");
            }
        }

        protected void GetContactDetail()
        {
            int bidder_seq = GetBidderSeq();
            BidderInfo info = bllBidder.GetBidderContact(bidder_seq);
            if (info != null)
            {
                lblGfmisCode.Text = info.InfoMasContact.Gfmis_code;
                lblContactGroup.Text = info.InfoMasContact.InfoGroup.Name;
                lblNameTh.Text = info.InfoMasContact.Name_th + (info.InfoMasContact.Name_eng.Length > 0 ? "(" + info.InfoMasContact.Name_eng + ")" : "");
                lblAddress.Text = info.InfoMasContact.All_address;
                lblTel.Text = info.InfoMasContact.Tel;
                lblEmail.Text = info.InfoMasContact.Email;
                hdBidderType.Value = (info.InfoPurchaseRequest.Seq != null ? "Pr" : "Bid");
                if (info.InfoPurchaseRequest.Seq != null)
                {
                    hdYearType.Value = info.InfoPurchaseRequest.InfoYearType.Seq.ToString();
                    hdBgmYear.Value = info.InfoPurchaseRequest.BgmYear.ToString();
                }
                else
                {
                    hdYearType.Value = info.InfoBid.InfoYearType.Seq.ToString();
                    hdBgmYear.Value = info.InfoBid.Year.ToString();
                }

                if (info.DueDay != null)
                {
                    rdbDuration.Checked = true;
                    txtDurationReq.Text = info.DueDay.ToString();
                    cbDurationType.SelectedValue = info.InfoDurationType.Seq.ToString();
                }
                else if (info.DueDate != null)
                {
                    rdbDate.Checked = true;
                    txtDateReq.Text = ((DateTime)info.DueDate).ToString("dd/MM/yyyy");
                }

                if (info.DueDay == null & info.DueDate == null)
                {
                    rdbDuration.Checked = true;
                }
            }
        }

        protected int GetBidderSeq()
        {
            int seq = Convert.ToInt32(Request.QueryString["sl"]);
            return seq;
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "Installment")
            {
                LoadGridInstallment();
            }
            else if (e.Argument == "Conclusion")
            {
                LoadGridConclusion();
            }
        }

        #region Tab ข้อมูลหลัก

        protected void LoadDurationType()
        {
            IList<SysDurationTypeInfo> infoList = bllDurationType.GetSysDurationType();
            cbDurationType.DataSource = infoList;
            cbDurationType.DataBind();
        }

        protected void nextButton_Detail_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Item',1);");
        }

        #endregion

        #region tab รายการพัสดุ

        protected void LoadGridItem()
        {
            IList<PurchaseOrderInstallmentItemInfo> infoListInstallItem = new List<PurchaseOrderInstallmentItemInfo>();
            infoListInstallItem = bllInstallItem.GetBidderQuotationFromBidder(GetBidderSeq());
            Grid_Item.DataSource = infoListInstallItem;
            Grid_Item.MasterTableView.GroupByExpressions.Clear();
            GridGroupByExpression ge = new GridGroupByExpression(Grid_Item.Columns[0]);
            Grid_Item.MasterTableView.GroupByExpressions.Add(ge);
            Grid_Item.DataBind();
            ViewState["Item"] = infoListInstallItem;
        }

        protected void Grid_Item_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridItem();
        }

        protected void Grid_Item_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                double exvat = 0;
                double vat = 0;
                double amount = 0;
                GridDataItem dataBoundItem = e.Item as GridDataItem;

                if (((Label)(dataBoundItem["ExVatAmount"].FindControl("lblExVatAmount"))).Text.Length > 0)
                {
                    exvat = double.Parse(((Label)(dataBoundItem["ExVatAmount"].FindControl("lblExVatAmount"))).Text);
                }
                if (((Label)(dataBoundItem["VatAmount"].FindControl("lblVatAmount"))).Text.Length > 0)
                {
                    vat = double.Parse(((Label)(dataBoundItem["VatAmount"].FindControl("lblVatAmount"))).Text);
                }
                if (((Label)(dataBoundItem["NetAmount"].FindControl("lblNetAmount"))).Text.Length > 0)
                {
                    amount = double.Parse(((Label)(dataBoundItem["NetAmount"].FindControl("lblNetAmount"))).Text);
                }

                totalExvat += exvat;
                totalVat += vat;
                totalAmount += amount;

                //if (!Object.Equals(target, null))
                //{
                //    if (!Object.Equals(this.TipItemDetail, null))
                //    {
                //        this.TipItemDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["InfoItem.Seq"].Text, true);
                //    }
                //}
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["Descr"].Controls.Add(new LiteralControl("<div align='right' style='color: Black; font-weight: bold;'>วงเงินจัดหาทั้งหมด :</div> "));
                ((Label)footer["ExVatAmount"].FindControl("lblTotalExVatAmount")).Text = totalExvat.ToString("###,###,##0.000");
                ((Label)footer["VatAmount"].FindControl("lblTotalVatAmount")).Text = totalVat.ToString("###,###,##0.000");
                ((Label)footer["NetAmount"].FindControl("lblTotalNetAmount")).Text = totalAmount.ToString("###,###,##0.000");
            }
        }

        protected void backButton_Item_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Detail',0);");
        }

        protected void nextButton_Item_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Committee',2);");
        }

        #endregion

        #region tab คณะกรรมการ

        protected void LoadGridCommittee()
        {
            IList<PurchaseOrderCommitteeInfo> infoListCommittee = new List<PurchaseOrderCommitteeInfo>();
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PurchaseOrderCommitteeInfo>)ViewState["Committee"];
            }
            else
            {
                int seq = GetBidderSeq();
                if (hdBidderType.Value == "Pr")
                {
                    infoListCommittee = bllPoCommittee.GetPurchaseOrderCommitteeFromPurchaseRequest(seq);
                }
                else
                {
                    infoListCommittee = bllPoCommittee.GetPurchaseOrderCommitteeFromBid(seq);
                }
                ViewState["Committee"] = infoListCommittee;
            }
            Grid_Committee.DataSource = infoListCommittee;
            GridGroupByExpression geFunction = new GridGroupByExpression(Grid_Committee.Columns[2]);
            GridGroupByExpression geRefNo = new GridGroupByExpression(Grid_Committee.Columns[3]);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geFunction);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geRefNo);
            Grid_Committee.DataBind();

            cmdFac.GridCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
        }

        protected void LoadCommitteeFunction()
        {
            IList<MasterCommitteeFunctionInfo> infoList = bllComFunction.GetMasterCommitteeFunction();
            cbCommitteeFunction.DataSource = infoList;
            cbCommitteeFunction.DataBind();
        }

        protected void LoadCommitteePosition()
        {
            IList<MasterCommitteePositionInfo> infoList = bllComPosition.GetMasterCommitteePosition();
            cbCommitteePosition.DataSource = infoList;
            cbCommitteePosition.DataBind();
        }

        protected void Grid_Committee_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCommittee();
        }

        protected void Grid_Committee_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Image image = (Image)dataBoundItem["Image"].FindControl("Image1");
                if (dataBoundItem["InfoRecord.InfoStatus.Status"].Text == "W")
                {
                    image.ImageUrl = "../Image/Grid/Update.gif";
                }
                else
                {
                    image.ImageUrl = "../Image/Grid/Cancel.gif";
                }
            }
        }

        protected void rblCommitteeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            panelInternal.Visible = (rblCommitteeType.SelectedValue == "1");
            panelExternal.Visible = (rblCommitteeType.SelectedValue == "2");
            LoadValidationCommittee();
        }

        protected void cbCommitteeInternalName_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbCommitteeInternalName.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(200);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(150);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(190);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)cbCommitteeInternalName.Items[j].FindControl("tableCommmitteeInternalName")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void AddNew_Committee_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
            LoadValidationCommittee();
        }

        protected void btnDelete_Committee_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderCommitteeInfo> infoListCommittee = new List<PurchaseOrderCommitteeInfo>();
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PurchaseOrderCommitteeInfo>)ViewState["Committee"];
            }
            int[] data_value = new int[Grid_Committee.MasterTableView.GetSelectedItems().Length];
            int item = Grid_Committee.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_Committee.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                infoListCommittee[data_value[i]].DeleteReason = txtDeleteReason.Text;
                infoListCommittee[data_value[i]].InfoRecord.InfoStatus.Status = SystemInfo._DeleteRecordStatus;
                infoListCommittee[data_value[i]].InfoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoListCommittee[data_value[i]].InfoRecord.Updated_when = DateTime.Now;
            }

            ViewState["Committee"] = infoListCommittee;
            LoadGridCommittee();
        }

        protected void Delete_Committee_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_Committee.MasterTableView.GetSelectedItems().Length];
            int item = Grid_Committee.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_Committee.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<PurchaseOrderCommitteeInfo>)ViewState["Committee"]).RemoveAt(data_value[i]);
            }

            LoadGridCommittee();
        }

        protected void AddNewSave_Committee_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderCommitteeInfo> infoListCommittee = new List<PurchaseOrderCommitteeInfo>();
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PurchaseOrderCommitteeInfo>)ViewState["Committee"];
            }

            PurchaseOrderCommitteeInfo info = new PurchaseOrderCommitteeInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            MasterCommitteePositionInfo infoPosition = new MasterCommitteePositionInfo();
            MasterCommitteeFunctionInfo infoFunction = new MasterCommitteeFunctionInfo();
            HrmEmployeeInfo infoEmployeeDetail = new HrmEmployeeInfo();
            SysCommitteeTypeInfo infoType = new SysCommitteeTypeInfo();
            RecordInfo infoRecord = new RecordInfo();
            SysRecordStatusInfo infoStatus = new SysRecordStatusInfo();

            info.Ref_no = Convert.ToInt32(txtCommitteeRefno.Value);
            infoType.Seq = Convert.ToInt32(rblCommitteeType.SelectedValue);
            infoType.Name = (rblCommitteeType.SelectedItem.Text);
            infoPosition.Seq = Convert.ToInt32(cbCommitteePosition.SelectedValue);
            infoPosition.Name = cbCommitteePosition.SelectedItem.Text;
            infoFunction.Seq = Convert.ToInt32(cbCommitteeFunction.SelectedValue);
            infoFunction.Name = cbCommitteeFunction.SelectedItem.Text;
            if (infoType.Seq == 1) //เป็นบุคลากรภายใน
            {
                infoEmployee.Seq = Convert.ToInt32(cbCommitteeInternalName.SelectedValue);
                infoEmployee.Name = cbCommitteeInternalName.Text;
                infoEmployeeDetail = bllEmployee.GetHrmEmployee(Convert.ToInt32(infoEmployee.Seq));
                info.Name = infoEmployee.Name;
                info.Descr = (infoEmployeeDetail.InfoJobSite.Name.Length > 0 ? " <b>หน่วยงาน : </b>" + infoEmployeeDetail.InfoJobSite.Name : "")
                    + (infoEmployeeDetail.InfoPosition.Name.Length > 0 ? " <b>ตำแหน่ง :</b>" + infoEmployeeDetail.InfoPosition.Name : "")
                    + (infoEmployeeDetail.InfoClass.Name.Length > 0 ? " <b>ระดับ :</b>" + infoEmployeeDetail.InfoClass.Name : "");
            }
            else
            {
                info.Ex_name = txtCommitteeExternalName.Text;
                info.Ex_descr = txtCommitteeExternalDescr.Text;
                info.Name = info.Ex_name;
                info.Descr = info.Ex_descr;
            }
            infoStatus.Status = SystemInfo._WorkRecordStatus;
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.InfoType = infoType;
            info.InfoExployee = infoEmployee;
            info.InfoPosition = infoPosition;
            info.InfoFunction = infoFunction;
            infoRecord.InfoStatus = infoStatus;
            info.InfoRecord = infoRecord;
            infoListCommittee.Add(info);
            ResetCommittee();
            ViewState["Committee"] = infoListCommittee;
            LoadGridCommittee();
        }

        protected void ResetCommittee()
        {
            txtCommitteeRefno.Text = "";
            cbCommitteeInternalName.ClearSelection();
            cbCommitteeInternalName.Text = "";
            txtCommitteeExternalName.Text = "";
            txtCommitteeExternalDescr.Text = "";
            cbCommitteePosition.ClearSelection();
            cbCommitteePosition.Text = "";
            cbCommitteeFunction.ClearSelection();
            cbCommitteeFunction.Text = "";
        }

        protected void ShowGrid_Committee_Click(object sender, EventArgs e)
        {
            cmdFac.GridCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
        }

        protected void LoadValidationCommittee()
        {
            RequiredFieldValidator valCommitteeRefno = new RequiredFieldValidator();
            valCommitteeRefno.ID = "ValtxtCommitteeRefno";
            valCommitteeRefno.ControlToValidate = "txtCommitteeRefno";
            valCommitteeRefno.SetFocusOnError = true;
            valCommitteeRefno.Display = ValidatorDisplay.Dynamic;
            valCommitteeRefno.ErrorMessage = "* กรุณาระบุชุดที่ *";
            panelValtxtCommitteeRefno.Controls.Add(valCommitteeRefno);
            RequiredFieldValidator valCommitteeInternalName = new RequiredFieldValidator();
            valCommitteeInternalName.ID = "ValcbCommitteeInternalName";
            valCommitteeInternalName.ControlToValidate = "cbCommitteeInternalName";
            valCommitteeInternalName.SetFocusOnError = true;
            valCommitteeInternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeInternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValcbCommitteeInternalName.Controls.Add(valCommitteeInternalName);
            RequiredFieldValidator valCommitteeExternalName = new RequiredFieldValidator();
            valCommitteeExternalName.ID = "ValtxtCommitteeExternalName";
            valCommitteeExternalName.ControlToValidate = "txtCommitteeExternalName";
            valCommitteeExternalName.SetFocusOnError = true;
            valCommitteeExternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeExternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValtxtCommitteeExternalName.Controls.Add(valCommitteeExternalName);
            RequiredFieldValidator valCommitteePosition = new RequiredFieldValidator();
            valCommitteePosition.ID = "ValcbCommitteePosition";
            valCommitteePosition.ControlToValidate = "cbCommitteePosition";
            valCommitteePosition.SetFocusOnError = true;
            valCommitteePosition.Display = ValidatorDisplay.Dynamic;
            valCommitteePosition.ErrorMessage = "* กรุณาระบุตำแหน่งกรรมการ *";
            panelValcbCommitteePosition.Controls.Add(valCommitteePosition);
            RequiredFieldValidator valCommitteeFunction = new RequiredFieldValidator();
            valCommitteeFunction.ID = "ValcbCommitteeFunction";
            valCommitteeFunction.ControlToValidate = "cbCommitteeFunction";
            valCommitteeFunction.SetFocusOnError = true;
            valCommitteeFunction.Display = ValidatorDisplay.Dynamic;
            valCommitteeFunction.ErrorMessage = "* กรุณาระบุหน้าที่กรรมการ *";
            panelValcbCommitteeFunction.Controls.Add(valCommitteeFunction);
        }

        protected void backButton_Committee_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Item',1);");
        }

        protected void nextButton_Committee_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Penalty',3);");
        }

        protected void OnAjaxUpdateCommittee(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTipCommittee(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTipCommittee(string elementID, UpdatePanel panel)
        {
            Control ctrl = Page.LoadControl("../UserControl/TIP_Purchase_Order_Committee_History.ascx");
            //((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Order_Committee_History)ctrl).GetBidderSeq = new CallBackHandleReturnInt(GetBidderSeq);
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        #endregion

        #region tab กำหนดการปรับ

        protected void LoadGridPenalty()
        {
            IList<PurchaseOrderPenaltyInfo> infoListPenalty = new List<PurchaseOrderPenaltyInfo>();
            if (ViewState["Penalty"] != null)
            {
                infoListPenalty = (List<PurchaseOrderPenaltyInfo>)ViewState["Penalty"];
            }
            Grid_Penalty.DataSource = infoListPenalty;
            Grid_Penalty.DataBind();
            cmdFac.GridCommand(panelList_Penalty, panelGrid_Penalty, panelCommand_Penalty);
        }

        protected void LoadPenaltyCount()
        {
            IList<SysPenaltyCountInfo> info = bllPenaltyCount.GetSysPenaltyCount();
            cbPenaltyCount.DataSource = info;
            cbPenaltyCount.DataBind();
        }

        protected void LoadPenaltyRateType()
        {
            IList<SysPenaltyRateTypeInfo> info = bllPenaltyRateType.SysPenaltyRateType();
            cbPenaltyRateType.DataSource = info;
            cbPenaltyRateType.DataBind();
        }

        protected void Grid_Penalty_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridPenalty();
        }

        protected void AddNew_Penalty_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Penalty, panelGrid_Penalty, panelCommand_Penalty);
            lblPenaltyType.Text = rblPenaltyType.SelectedItem.Text;
            LoadValidatePenalty();
            lblPenaltyType.Visible = true;
        }

        private void LoadValidatePenalty()
        {
            RequiredFieldValidator valPenaltyName = new RequiredFieldValidator();
            valPenaltyName.ID = "ValtxtPenaltyName";
            valPenaltyName.ControlToValidate = "txtPenaltyName";
            valPenaltyName.SetFocusOnError = true;
            valPenaltyName.Display = ValidatorDisplay.Dynamic;
            valPenaltyName.ErrorMessage = "* กรุณาระบุปรับเนื่องจาก *";
            panelValtxtPenaltyName.Controls.Add(valPenaltyName);

            RequiredFieldValidator valPenaltyRate = new RequiredFieldValidator();
            valPenaltyRate.ID = "ValtxtPenaltyRate";
            valPenaltyRate.ControlToValidate = "txtPenaltyRate";
            valPenaltyRate.SetFocusOnError = true;
            valPenaltyRate.Display = ValidatorDisplay.Dynamic;
            valPenaltyRate.ErrorMessage = "* กรุณาระบุอัตราค่าปรับ *";

            RequiredFieldValidator valPenaltyRateType = new RequiredFieldValidator();
            valPenaltyRateType.ID = "ValcbPenaltyRateType";
            valPenaltyRateType.ControlToValidate = "cbPenaltyRateType";
            valPenaltyRateType.SetFocusOnError = true;
            valPenaltyRateType.Display = ValidatorDisplay.Dynamic;
            valPenaltyRateType.ErrorMessage = "* กรุณาระบุหน่วยค่าปรับ *";

            RequiredFieldValidator valPenaltyCount = new RequiredFieldValidator();
            valPenaltyCount.ID = "ValcbPenaltyCount";
            valPenaltyCount.ControlToValidate = "cbPenaltyCount";
            valPenaltyCount.SetFocusOnError = true;
            valPenaltyCount.Display = ValidatorDisplay.Dynamic;
            valPenaltyCount.ErrorMessage = "* กรุณาระบุระยะเวลาค่าปรับ *";

            panelValPanaltyRate.Controls.Add(valPenaltyRate);
            panelValPanaltyRate.Controls.Add(valPenaltyRateType);
            panelValPanaltyRate.Controls.Add(valPenaltyCount);
        }

        protected void Delete_Penalty_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_Penalty.MasterTableView.GetSelectedItems().Length];
            int item = Grid_Penalty.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_Penalty.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<PurchaseOrderPenaltyInfo>)ViewState["Penalty"]).RemoveAt(data_value[i]);
            }

            LoadGridPenalty();
        }

        protected void AddNewSave_Penalty_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderPenaltyInfo> infoListPenalty = new List<PurchaseOrderPenaltyInfo>();
            PurchaseOrderPenaltyInfo info = new PurchaseOrderPenaltyInfo();
            SysPenaltyRateTypeInfo infoSysPenaltyRateType = new SysPenaltyRateTypeInfo();
            SysPenaltyCountInfo infoPenaltyCount = new SysPenaltyCountInfo();
            if (ViewState["Penalty"] != null)
            {
                infoListPenalty = (List<PurchaseOrderPenaltyInfo>)ViewState["Penalty"];
            }

            info.Name = txtPenaltyName.Text;
            info.Descr = txtPenaltyDescr.Text;
            info.Rate = Convert.ToDouble(txtPenaltyRate.Text);
            infoSysPenaltyRateType.Seq = Convert.ToInt32(cbPenaltyRateType.SelectedValue);
            infoPenaltyCount.Seq = Convert.ToInt32(cbPenaltyCount.SelectedValue);

            if (panelLeast.Visible && txtLeast.Text != "")
                info.Least = Convert.ToDouble(txtLeast.Text);
            info.PenaltyDetail = txtPenaltyRate.Text + " " + cbPenaltyRateType.Text + " ต่อ " + cbPenaltyCount.Text +
                ((txtLeast.Text != "") ? "และไม่ต่ำกว่าวันละ " + txtLeast.Text + " บาท" : "");

            info.InfoPenaltyRateType = infoSysPenaltyRateType;
            info.InfoPenaltyCount = infoPenaltyCount;

            infoListPenalty.Add(info);
            ViewState["Penalty"] = infoListPenalty;
            LoadGridPenalty();
        }

        protected void ShowGrid_Penalty_Click(object sender, EventArgs e)
        {
            cmdFac.GridCommand(panelList_Penalty, panelGrid_Penalty, panelCommand_Penalty);
        }

        protected void backButton_Penalty_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Committee',2);");
        }

        protected void nextButton_Penalty_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Installment',4);");
        }

        #endregion

        #region tab งวดการส่งมอบ

        protected void LoadGridInstallment()
        {
            IList<PurchaseOrderInstallmentInfo> infoListInstallment = new List<PurchaseOrderInstallmentInfo>();
            if (ViewState["Installment"] != null)
            {
                infoListInstallment = (List<PurchaseOrderInstallmentInfo>)ViewState["Installment"];
            }

            foreach (PurchaseOrderInstallmentInfo info in infoListInstallment)
            {
                double sumAmount = 0;
                if (Session["InstallmentItem_" + GetBidderSeq().ToString() + "_" + info.InstallNumber.ToString()] != null)
                {
                    IList<PurchaseOrderInstallmentItemInfo> infoListItem = new List<PurchaseOrderInstallmentItemInfo>();
                    infoListItem = (List<PurchaseOrderInstallmentItemInfo>)Session["InstallmentItem_" + GetBidderSeq().ToString() + "_" + info.InstallNumber.ToString()];
                    info.InfoListItem = infoListItem;
                    foreach (PurchaseOrderInstallmentItemInfo infoItem in infoListItem)
                    {
                        sumAmount += (infoItem.NetAmount.ToString().Length > 0 ? Convert.ToDouble(infoItem.NetAmount) : 0);
                    }
                    info.SumAmount = sumAmount;

                    if (txtRedemption.Text.Length > 0)
                    {
                        info.RedemptionAmount = info.SumAmount * (Convert.ToDouble(txtRedemption.Text) / 100);
                        info.NetAmount = info.SumAmount - info.RedemptionAmount;
                    }
                }
            }

            Grid_Installment.DataSource = infoListInstallment;
            Grid_Installment.DataBind();

            Grid_Installment.Columns[1].Visible = (hdCheckDuration.Value == "1");
            Grid_Installment.Columns[2].Visible = (hdCheckDuration.Value == "0");
            lblHeaderInstallment.Text = (hdCheckDuration.Value == "1"
                ? "(ส่งมอบภายใน " + hdDuration.Value + " " + hdDurationTypeText.Value + ")"
                : "(ส่งมอบภายในวันที่ " + hdDurationDate.Value + ")");

            lblHeaderInstallment.Text += (txtRedemption.Text.Length > 0 ? "(หักประกันผลงานงวดละ " + txtRedemption.Text + " %)" : "");
            Edit_Installment.Visible = true;
            EditSave_Installment.Visible = false;
            Cancel_Installment.Visible = false;
        }

        protected void Edit_Installment_Click(object sender, EventArgs e)
        {
            this.IsItemInEditMode = true;
            LoadGridInstallment();
            Edit_Installment.Visible = false;
            EditSave_Installment.Visible = true;
            Cancel_Installment.Visible = true;
        }

        protected void Cancel_Installment_Click(object sender, EventArgs e)
        {
            this.IsItemInEditMode = false;
            LoadGridInstallment();
            Edit_Installment.Visible = true;
            EditSave_Installment.Visible = false;
            Cancel_Installment.Visible = false;
        }

        protected void EditSave_Installment_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderInstallmentInfo> infoList = new List<PurchaseOrderInstallmentInfo>();
            foreach (GridDataItem data in Grid_Installment.MasterTableView.Items)
            {
                PurchaseOrderInstallmentInfo info = new PurchaseOrderInstallmentInfo();
                SysDurationTypeInfo infoDurationType = new SysDurationTypeInfo();
                info.Seq = Convert.ToInt32(data["Seq"].Text);
                info.InstallNumber = Convert.ToInt32(((HyperLink)data["InstallNumber"].FindControl("HyperLink1")).Text);
                if (Grid_Installment.Columns[1].Visible)
                {
                    if (((RadNumericTextBox)data["Duration"].FindControl("txtDurationReq")).Text.Length > 0)
                    {
                        info.RequireDuration = Convert.ToInt32(((RadNumericTextBox)data["Duration"].FindControl("txtDurationReq")).Text);
                    }
                    else
                    {
                        info.RequireDuration = null;
                    }
                    infoDurationType.Seq = Convert.ToInt32(((Label)data["Duration"].FindControl("lblDurationTypeSeq")).Text);
                    info.DurationDescr = (info.RequireDuration != null ? info.RequireDuration.ToString() + " "
                        + ((Label)data["Duration"].FindControl("lblDurationTypeText")).Text
                        + "นับจากวันที่ลงนามในสัญญา"
                        : "");
                }
                if (Grid_Installment.Columns[2].Visible)
                {
                    if (((RadMaskedTextBox)data["DurationDate"].FindControl("txtDateReq")).Text.Length > 0)
                    {
                        info.RequireDate = Convert.ToDateTime(((RadMaskedTextBox)data["DurationDate"].FindControl("txtDateReq")).TextWithLiterals);
                        info.DeliveryDate = Convert.ToDateTime(((RadMaskedTextBox)data["DurationDate"].FindControl("txtDateReq")).TextWithLiterals);
                    }
                    else
                    {
                        info.RequireDate = null;
                    }
                    info.DurationDateDescr = (info.RequireDate != null ? Convert.ToDateTime(info.RequireDate).ToString("dd/MM/yyyy") : "");
                }

                info.InfoDurationType = infoDurationType;
                info.SumAmount = Convert.ToDouble(data["SumAmount"].Text);
                infoList.Add(info);
            }
            ViewState["Installment"] = infoList;
            LoadGridInstallment();
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            int install_number = (txtInstallNumber.Text.Length > 0 ? Convert.ToInt32(txtInstallNumber.Text) : 0);
            int nCount = 1;
            IList<PurchaseOrderInstallmentInfo> infoList = new List<PurchaseOrderInstallmentInfo>();
            for (int i = 0; i < install_number; i++)
            {
                PurchaseOrderInstallmentInfo info = new PurchaseOrderInstallmentInfo();
                IList<PurchaseOrderInstallmentItemInfo> infoListItem = new List<PurchaseOrderInstallmentItemInfo>();
                SysDurationTypeInfo infoType = new SysDurationTypeInfo();

                info.Seq = nCount;
                info.InstallNumber = nCount;
                info.SumAmount = 0;
                info.InfoDurationType = infoType;
                infoListItem = bllInstallItem.GetBidderQuotationFromBidderForInstallment(GetBidderSeq(), nCount);
                Session["InstallmentItem_" + GetBidderSeq().ToString() + "_" + info.InstallNumber.ToString()] = infoListItem;
                info.InfoListItem = infoListItem;
                infoList.Add(info);
                nCount++;
            }

            ViewState["Installment"] = infoList;
            LoadGridInstallment();
        }

        protected void Grid_Installment_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridInstallment();
        }

        protected void Grid_Installment_ItemDataBound(object sender, GridItemEventArgs e)
        {
            IList<SysDurationTypeInfo> infoList = bllDurationType.GetSysDurationType();
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Label lblDurationText = ((Label)(dataBoundItem["Duration"].FindControl("lblDurationTypeText")));
                Label lblDurationSeq = ((Label)(dataBoundItem["Duration"].FindControl("lblDurationTypeSeq")));
                lblDurationText.Text = hdDurationTypeText.Value;
                lblDurationSeq.Text = hdDurationTypeSeq.Value;
            }
        }

        protected void backButton_Installment_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Penalty',3);");
        }

        protected void nextButton_Installment_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Conclusion',5);");
        }

        protected bool IsItemInEditMode
        {
            get { return this.isItemInEditMode; }
            set { this.isItemInEditMode = value; }
        }

        #endregion

        #region tab สรุปการส่งมอบ

        protected void LoadGridConclusion()
        {
            IList<PurchaseOrderInstallmentInfo> infoListInstallment = new List<PurchaseOrderInstallmentInfo>();
            IList<PurchaseOrderInstallmentItemInfo> infoListInstallItem = new List<PurchaseOrderInstallmentItemInfo>();
            IList<PurchaseOrderInstallmentItemInfo> infoListQuotationItem = new List<PurchaseOrderInstallmentItemInfo>();

            if (ViewState["Installment"] != null)
            {
                infoListInstallment = (List<PurchaseOrderInstallmentInfo>)ViewState["Installment"];
            }

            if (infoListInstallment.Count > 0)
            {
                foreach (PurchaseOrderInstallmentInfo info in infoListInstallment)
                {
                    if (Session["InstallmentItem_" + GetBidderSeq().ToString() + "_" + info.InstallNumber.ToString()] != null)
                    {
                        IList<PurchaseOrderInstallmentItemInfo> infoListItem = new List<PurchaseOrderInstallmentItemInfo>();
                        infoListItem = (List<PurchaseOrderInstallmentItemInfo>)Session["InstallmentItem_" + GetBidderSeq().ToString() + "_" + info.InstallNumber.ToString()];
                        foreach (PurchaseOrderInstallmentItemInfo infoItem in infoListItem)
                        {
                            infoListInstallItem.Add(infoItem);
                        }
                    }
                }

                infoListQuotationItem = bllInstallItem.GetBidderQuotationFromBidderForConclusion(GetBidderSeq());

                foreach (PurchaseOrderInstallmentItemInfo info in infoListInstallItem)
                {
                    foreach (PurchaseOrderInstallmentItemInfo infoItem in infoListQuotationItem)
                    {
                        if (info.InfoBidderQuotation.InfoPrItem.Seq == infoItem.InfoBidderQuotation.InfoPrItem.Seq)
                        {
                            info.InfoBidderQuotation.InfoPrItem.ItemName = infoItem.InfoBidderQuotation.InfoPrItem.InfoItem.Name;
                            info.InfoBidderQuotation.InfoPrItem.ItemName += " (ฐานภาษี : " + info.InfoBidderQuotation.InfoBidder.InfoVat.Name + ")"; 
                            break;
                        }
                    }
                }
            }
            Grid_Conclusion.DataSource = infoListInstallItem;
            Grid_Conclusion.MasterTableView.GroupByExpressions.Clear();
            //GridGroupByExpression geVat = new GridGroupByExpression(Grid_Conclusion.Columns[0]);
            //Grid_Conclusion.MasterTableView.GroupByExpressions.Add(geVat);
            GridGroupByExpression geItem = new GridGroupByExpression(Grid_Conclusion.Columns[1]);
            Grid_Conclusion.MasterTableView.GroupByExpressions.Add(geItem);
            Grid_Conclusion.DataBind();
        }

        protected void Grid_Conclusion_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridConclusion();
        }

        protected void backButton_Conclusion_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Installment',4);");
        }

        protected void nextButton_Conclusion_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Collateral',6);");
        }

        #endregion

        #region tab หลักประกัน

        protected void LoadGridCollateral()
        {
            IList<PurchaseOrderCollateralInfo> infoList = new List<PurchaseOrderCollateralInfo>();
            if (ViewState["Collateral"] != null)
            {
                infoList = (List<PurchaseOrderCollateralInfo>)ViewState["Collateral"];
            }
            Grid_Collateral.DataSource = infoList;
            GridGroupByExpression ge = new GridGroupByExpression(Grid_Collateral.Columns[1]);
            Grid_Collateral.MasterTableView.GroupByExpressions.Add(ge);
            Grid_Collateral.DataBind();
            cmdFac.GridCommand(panelList_Collateral, panelGrid_Collateral, panelCommand_Collateral);
        }

        protected void LoadCollateralCateory()
        {
            IList<SysCollateralCategoryInfo> info = bllColcategory.GetSysCollateralCategory();
            cbCollateralCategory.DataSource = info;
            cbCollateralCategory.DataBind();
        }

        protected void LoadCollateralType()
        {
            IList<SysCollateralTypeInfo> info = bllColType.GetSysCollateralTypeNonFinance();
            cbCollateralType.DataSource = info;
            cbCollateralType.DataBind();
        }

        protected void Grid_Collateral_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCollateral();
        }

        protected void AddNew_Collateral_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Collateral, panelGrid_Collateral, panelCommand_Collateral);
            LoadValidateCollateral();
        }

        private void LoadValidateCollateral()
        {
            RequiredFieldValidator valCategory = new RequiredFieldValidator();
            valCategory.ID = "ValcbCollateralCategory";
            valCategory.ControlToValidate = "cbCollateralCategory";
            valCategory.SetFocusOnError = true;
            valCategory.Display = ValidatorDisplay.Dynamic;
            valCategory.ErrorMessage = "* กรุณาระบุชนิดหลักประกัน *";
            panelValcbCollateralCategory.Controls.Add(valCategory);
            RequiredFieldValidator valRefNo = new RequiredFieldValidator();
            valRefNo.ID = "ValtxtCollateralRefNo";
            valRefNo.ControlToValidate = "txtCollateralRefNo";
            valRefNo.SetFocusOnError = true;
            valRefNo.Display = ValidatorDisplay.Dynamic;
            valRefNo.ErrorMessage = "* กรุณาระบุหมายเลขอ้างอิง *";
            panelValtxtCollateralRefNo.Controls.Add(valRefNo);
            RequiredFieldValidator valCollateralType = new RequiredFieldValidator();
            valCollateralType.ID = "ValcbCollateralType";
            valCollateralType.ControlToValidate = "cbCollateralType";
            valCollateralType.SetFocusOnError = true;
            valCollateralType.Display = ValidatorDisplay.Dynamic;
            valCollateralType.ErrorMessage = "* กรุณาระบุประเภทหลักประกัน *";
            panelValcbCollateralType.Controls.Add(valCollateralType);
            RequiredFieldValidator valAmount = new RequiredFieldValidator();
            valAmount.ID = "ValtxtCollateralAmount";
            valAmount.ControlToValidate = "txtCollateralAmount";
            valAmount.SetFocusOnError = true;
            valAmount.Display = ValidatorDisplay.Dynamic;
            valAmount.ErrorMessage = "* กรุณาระบุจำนวนเงิน *";
            panelValtxtCollateralAmount.Controls.Add(valAmount);
            RequiredFieldValidator valDescr = new RequiredFieldValidator();
            valDescr.ID = "ValtxtCollateralDescr";
            valDescr.ControlToValidate = "txtCollateralDescr";
            valDescr.SetFocusOnError = true;
            valDescr.Display = ValidatorDisplay.Dynamic;
            valDescr.ErrorMessage = "* กรุณาระบุรายละเอียด *";
            panelValtxtCollateralDescr.Controls.Add(valDescr);
        }

        protected void Delete_Collateral_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_Collateral.MasterTableView.GetSelectedItems().Length];
            int item = Grid_Collateral.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_Collateral.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<PurchaseOrderCollateralInfo>)ViewState["Collateral"]).RemoveAt(data_value[i]);
            }

            LoadGridCollateral();
        }

        protected void AddNewSave_Collateral_Click(object sender, EventArgs e)
        {
            IList<PurchaseOrderCollateralInfo> infoList = new List<PurchaseOrderCollateralInfo>();
            PurchaseOrderCollateralInfo info = new PurchaseOrderCollateralInfo();
            SysCollateralCategoryInfo infoCategory = new SysCollateralCategoryInfo();
            SysCollateralTypeInfo infoType = new SysCollateralTypeInfo();

            if (ViewState["Collateral"] != null)
            {
                infoList = (List<PurchaseOrderCollateralInfo>)ViewState["Collateral"];
            }

            info.RefNo = txtCollateralRefNo.Text;
            infoCategory.Seq = Convert.ToInt32(cbCollateralCategory.SelectedValue);
            infoCategory.Name = cbCollateralCategory.SelectedItem.Text;
            infoType.Seq = Convert.ToInt32(cbCollateralType.SelectedValue);
            infoType.Name = cbCollateralType.SelectedItem.Text;
            info.Amount = Convert.ToDouble(txtCollateralAmount.Text);
            info.Descr = txtCollateralDescr.Text;

            info.InfoCategory = infoCategory;
            info.InfoType = infoType;

            infoList.Add(info);
            ViewState["Collateral"] = infoList;
            LoadGridCollateral();
        }

        protected void ShowGrid_Collateral_Click(object sender, EventArgs e)
        {
            cmdFac.GridCommand(panelList_Collateral, panelGrid_Collateral, panelCommand_Collateral);
        }

        protected void backButton_Collateral_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Conclusion',5);");
        }

        protected void nextButton_Collateral_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('File',7);");
        }

        #endregion

        #region tab เอกสารแนบ

        protected void LoadGridFile()
        {
            IList<DocumentInfo> infoListFile = new List<DocumentInfo>();
            if (ViewState["File"] != null)
            {
                infoListFile = (List<DocumentInfo>)ViewState["File"];
            }
            Grid_File.DataSource = infoListFile;
            Grid_File.DataBind();

            cmdFac.GridCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void ShowGrid_File_Click(object sender, EventArgs e)
        {
            LoadGridFile();
        }

        protected void AddNew_File_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_File, panelGrid_File, panelCommand_File);
            LoadValidateFile();
        }

        private void LoadValidateFile()
        {
            RequiredFieldValidator valFileName = new RequiredFieldValidator();
            valFileName.ID = "ValtxtFileName";
            valFileName.ControlToValidate = "txtFileName";
            valFileName.SetFocusOnError = true;
            valFileName.Display = ValidatorDisplay.Dynamic;
            valFileName.ErrorMessage = "* กรุณาระบุชื่อไฟล์ *";
            panelValtxtFileName.Controls.Add(valFileName);
            RequiredFieldValidator valAttachment = new RequiredFieldValidator();
            valAttachment.ID = "Valattachment";
            valAttachment.ControlToValidate = "attachment";
            valAttachment.SetFocusOnError = true;
            valAttachment.Display = ValidatorDisplay.Dynamic;
            valAttachment.ErrorMessage = "* กรุณาระบุที่อยู่ไฟล์ *";
            panelValattachment.Controls.Add(valAttachment);
        }

        protected void AddNewSave_File_Click(object sender, EventArgs e)
        {
            IList<DocumentInfo> infoListFile = new List<DocumentInfo>();
            FileInfo infoFile = new FileInfo(hdSourceFile.Value);
            DocumentInfo info = new DocumentInfo();
            RecordInfo infoRecord = new RecordInfo();
            if (ViewState["File"] != null)
            {
                infoListFile = (List<DocumentInfo>)ViewState["File"];
            }
            infoRecord.Created_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Created_when = DateTime.Now;
            info.File_info = infoFile;
            info.Name = txtFileName.Text;
            info.Dest_path = hdSourceFile.Value;
            info.InfoRecord = infoRecord;
            infoListFile.Add(info);
            ViewState["File"] = infoListFile;
            LoadGridFile();
        }

        protected void Delete_File_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_File.MasterTableView.GetSelectedItems().Length];
            int item = Grid_File.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_File.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<DocumentInfo>)ViewState["File"]).RemoveAt(data_value[i]);
            }

            LoadGridFile();
        }

        protected void Grid_File_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridFile();
        }

        protected void backButton_File_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Collateral',6);");
        }

        protected void finishButton_File_Click(object sender, EventArgs e)
        {
            SysDurationTypeInfo infoDurationType = new SysDurationTypeInfo();
            RecordInfo infoRecord = new RecordInfo();
            PurchaseOrderInfo info = new PurchaseOrderInfo();
            BidderInfo infoBidder = new BidderInfo();
            SysYearTypeInfo infoYearType = new SysYearTypeInfo();
            SysRecordStatusInfo infoRecordStatus = new SysRecordStatusInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            HrmJobSiteInfo infoJobSite = new HrmJobSiteInfo();
            PurchaseRequestInfo infoPurchaseRequest = bllPurchaseRequest.GetPurchaseRequestByBidder(GetBidderSeq());
            SysPoTypeInfo infoPoType = new SysPoTypeInfo();
            IList<PurchaseOrderCommitteeInfo> infoListCommittee = new List<PurchaseOrderCommitteeInfo>();
            IList<PurchaseOrderPenaltyInfo> infoListPenalty = new List<PurchaseOrderPenaltyInfo>();
            IList<PurchaseOrderInstallmentInfo> infoListInstallment = new List<PurchaseOrderInstallmentInfo>();
            IList<PurchaseOrderCollateralInfo> infoListCollateral = new List<PurchaseOrderCollateralInfo>();
            IList<DocumentInfo> infoListFile = new List<DocumentInfo>();
            string lastNumber;

            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PurchaseOrderCommitteeInfo>)ViewState["Committee"];
            }
            if (ViewState["Penalty"] != null)
            {
                infoListPenalty = (List<PurchaseOrderPenaltyInfo>)ViewState["Penalty"];
            }
            if (ViewState["Installment"] != null)
            {
                infoListInstallment = (List<PurchaseOrderInstallmentInfo>)ViewState["Installment"];
            }
            if (ViewState["Collateral"] != null)
            {
                infoListCollateral = (List<PurchaseOrderCollateralInfo>)ViewState["Collateral"];
            }
            if (ViewState["File"] != null)
            {
                infoListFile = (List<DocumentInfo>)ViewState["File"];
            }

            infoRecord.Created_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Created_when = DateTime.Now;

            info.Date = Convert.ToDateTime(txtDate.TextWithLiterals);
            info.Name = txtName.Text;
            info.Descr = txtDescr.Text;
            infoPoType.Seq = 2;
            info.CanInstallment = SystemInfo._YesStatus;
            infoBidder.Seq = GetBidderSeq();
            infoYearType.Seq = Convert.ToInt32(hdYearType.Value);
            info.BgmYear = Convert.ToInt32(hdBgmYear.Value);
            infoEmployee.Seq = 1;
            string[] strJobSite = GetUserJobSite(Convert.ToInt32(infoEmployee.Seq));
            infoJobSite.Seq = Convert.ToInt32(strJobSite[0]);
            infoRecordStatus.Status = SystemInfo._WorkRecordStatus;

            if (rdbDuration.Checked)
            {
                if (txtDurationReq.Text.Length > 0)
                {
                    info.RequireDuration = Convert.ToInt32(txtDurationReq.Value);
                    infoDurationType.Seq = Convert.ToInt32(cbDurationType.SelectedValue);
                }
            }
            if (rdbDate.Checked)
            {
                if (txtDateReq.Text.Length > 0)
                {
                    info.RequireDate = Convert.ToDateTime(txtDateReq.TextWithLiterals);
                }
            }

            infoRecord.InfoStatus = infoRecordStatus;
            info.InfoYearType = infoYearType;
            info.InfoDurationType = infoDurationType;
            info.InfoRecord = infoRecord;
            info.InfoBidder = infoBidder;
            info.InfoOrderEmp = infoEmployee;
            info.InfoOrderJobSite = infoJobSite;
            info.InfoPoType = infoPoType;

            try
            {
                lastNumber = bllPurchaseOrder.InsertContract(info, infoListCommittee, infoListPenalty, infoListInstallment, infoListCollateral, infoListFile);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            RadManager1.Alert("เลขที่รายการของท่านคือ : '" + lastNumber + "'");
            RadManager1.ResponseScripts.Add(@"CloseWindow();");
        }

        private string[] GetUserJobSite(int emp_seq)
        {
            return bllPersonal.GetUserJobSite(emp_seq);
        }

        protected void OnAjaxUpdateFile(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTipFile(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTipFile(string elementID, UpdatePanel panel)
        {
            Control ctrl = Page.LoadControl("../UserControl/TIP_Purchase_Order_File_History.ascx");
            //((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Order_Committee_History)ctrl).GetBidderSeq = new CallBackHandleReturnInt(GetBidderSeq);
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        #endregion
    }
}
